package com.project.bo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.project.bean.User;
import com.project.persistence.dao.UserDAOImpl;

public class UserBO {

	private static UserBO instance;

	private static HashMap<Integer,User> users = new HashMap<Integer, User>();

	private static Boolean cacheUpdated = Boolean.FALSE;

	public static UserBO getInstance() {
		if(instance == null) {
			instance = new UserBO();
		}
		return instance;
	}

	private UserBO() {

	}

	public Boolean insert(User user) {
		UserDAOImpl userDAO = new UserDAOImpl();
		Boolean result = userDAO.insert(user);
		
		if (result) {
			insertOnCache(userDAO.getUser(user));
		}

		return result;

	}

	public User getUserById(User user) {
		UserDAOImpl userDAO = new UserDAOImpl();
		User userFound = getFromCache(user);

		if(userFound == null) {

			userFound = userDAO.getUser(user);

			if (userFound != null) {
				insertOnCache(userFound);
			}
		}

		return userFound;
	}

	public User getUserByName(User user) {
		UserDAOImpl userDAO = new UserDAOImpl();
		
		User userFound = userDAO.getUser(user);

		return userFound;
	}

	public List<User> getAllUsers() {

		if (!cacheUpdated) {
			UserDAOImpl userDAO = new UserDAOImpl();
			List<User> userList = userDAO.getAll();

			for(User user: userList) {
				insertOnCache(user);
			}

			cacheUpdated = Boolean.TRUE;
		}

		return new ArrayList<User>(users.values());
	}

	private void insertOnCache(User user) {
		if (user != null) {
			users.put(user.getUserId(), user);
		}
	}

	private User getFromCache(User user) {
		User userResult = null;
		if (user.getUserId() != null) {
			userResult = users.get(user.getUserId());
		} else {
			for (User usr : users.values()) {
				if (usr.getUserName().equalsIgnoreCase(user.getUserName())) {
					userResult = usr;
					break;
				}
			}
		}

		return userResult;
	}

	public static void clearCache() {
		users.clear();
		users = null;
		users = new HashMap<Integer, User>();
		cacheUpdated = Boolean.FALSE;
	}

	public Boolean update(User user) {
		UserDAOImpl userDAO = new UserDAOImpl();
		Boolean result = userDAO.update(user);

		if (result) {
			insertOnCache(userDAO.getUser(user));
		}

		return result;
	}

	public Boolean disable(Integer userId) {
		User user = new User();

		user = users.get(userId);
		user.setActive(Boolean.FALSE);

		UserDAOImpl userDAO = new UserDAOImpl();
		Boolean result  = userDAO.disable(user);

		if (result) {
			insertOnCache(user);
		}

		return result;
	}


	public Boolean enable(Integer userId) {
		User user = new User();

		user = users.get(userId);
		user.setActive(Boolean.TRUE);

		UserDAOImpl userDAO = new UserDAOImpl();
		Boolean result  = userDAO.enable(user);

		if (result) {
			insertOnCache(user);
		}

		return result;
	}
}
